package com.twoscreen;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

public class LogServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger("com.twoscreen.ErrorLogServlet.java");
	private static final long serialVersionUID = 1L;
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) {
		UserService userService = UserServiceFactory.getUserService();
		User user = null;
		String userID = null;
		int code = 0;
		String status = null;
		String body = null;
		
		//Get the user
		try {
			user = userService.getCurrentUser();
			userID = user.getUserId();
		} catch (Exception e) {
			log.warning("Error getting the user: " + e);
		}
		
		//Get the parameters passed
		if (request.getParameter("code") != null) {
			code = Integer.parseInt(request.getParameter("code"));
			log.info("code received: " + code);
		}
		if (request.getParameter("status") != null) {
			status = request.getParameter("status");
			log.info("message received: " + status);
		}
		
		//Get the body
		StringBuilder sb = new StringBuilder();
		BufferedReader reader = null;
		try {
	        reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
	        for (String line; (line = reader.readLine()) != null;) {
	            sb.append(line);
	            log.info("adding: " + line);
	        }
	    } catch (IOException e) {
	    	log.severe("IO error reading from input stream: " + e);
		} finally {
	        if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
	    }
		body = sb.toString();
		
		switch (code) {
		case 1:
			//Log a info message
			log.info("Sent from: " + userID);
			log.info("Status: " + status);
			log.info(body);
			break;
			
		case 2:
			//Log a warning message
			log.warning("Sent from: " + userID);
			log.warning("Status: " + status);
			log.warning(body);
			break;
			
		case 3:
			//Log an error message
			log.severe("Sent from: " + userID);
			log.severe("Status: " + status);
			log.severe(body);
			break;
		
		default:
			break;
		}
	}

}
